from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView,ListCreateAPIView,UpdateAPIView,GenericAPIView,GenericAPIView
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from users.models import Address, User

from areas.models import Area
# Create your views here.
from areas.serializers import AreaSerializer, AddressSerializers


class AreaView(CacheResponseMixin,ListAPIView):
    # 查询所有省信息
    queryset = Area.objects.filter(parent=None)
    # 指定返回序列化器
    serializer_class = AreaSerializer


class AreasView(CacheResponseMixin,ListAPIView):
    # 查询所有市信息和区县信息
    # queryset = Area.objects.filter(parent_id=pk)
    # 指定返回序列化器
    serializer_class = AreaSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)

    # @cache_response()
    # def get(self):


class AddressView(ListCreateAPIView,UpdateAPIView):

    serializer_class = AddressSerializers

    def get(self, request, *args, **kwargs):
        # 获取所有地址信息
        address=self.get_queryset()
        # default_address_id=request.user.default_address_id
        default_address_id=request.user.default_address_id

        # 进行序列化处理,获取默认地址
        ser=self.get_serializer(address,many=True)

        return Response({'default_address_id':default_address_id,'address':ser.data})


    # queryset = Address.objects.filter(user)

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user,is_deleted=False)
    def delete(self,request,pk):
        address=self.get_object()
        address.is_deleted=True
        address.save()
        return Response({'message':'ok'})
# class StatusView(GenericAPIView):
#     def put(self,request,pk):
#
#         user=request.user
#         user.default_address_id=pk
#         user.save()
#
#         address = Address.objects.get(id=complex)
#         ser=AddressSerializers(address)
#
#         return Response(ser.data)

class StatusView(GenericAPIView):


    def put(self,request,pk):

        user=request.user

        user.default_address_id=pk

        user.save()

        address=Address.objects.get(id=pk)

        ser=AddressSerializers(address)

        return  Response(ser.data)
